var queryClassTermReportUrl = basePath + "/sys/student/groupup/json/queryClassTermReport";
var batchCreatePdfUrl = basePath + "/sys/student/groupup/json/batchCreate";
var updateStudentTermReport = basePath + "/sys/student/groupup/json/updateStudentTermReport";
var termListUrl = basePath + "/sys/dict/termList";

var dataGrid;
$(function() {
	initTermList();
	$('#files').filebox({
        buttonText: '选择文件',
        buttonAlign: 'left'
    })
});

function loadData() {
	dataGrid = $('#studentDg').datagrid({
		url : queryClassTermReportUrl,
		toolbar: '#tb',
		fit : true,
		fitColumns : true,
		border : true,
		pagination : false,
		idField : 'id',
		pageSize : config.pageSize,
		autoRowHeight : 140,
		pageList : config.pageList,
		nowrap : true,
		striped : true,
		singleSelect: true,
		rownumbers : true,
		collapsible: true,
		queryParams: {
			termId: $("#termId").val(),
			termType: $("#termType").val(),
			grade: $("#grade").val().split(",")[0],
			studyType: $("#grade").val().split(",")[1],
			clazz: $("#clazz").val()
		},
		frozenColumns : [ [  {
			field : 'id',
			checkbox : false,
			hidden: true
		}, {
			field : 'studentNo',
			title : '学号',
		}, {
			field : 'studentName',
			title : '学生姓名',
		} ] ],
		columns : [ [  {
			field : 'politicsNormalScore',
			title : '政治平时成绩',
			editor: {type:'numberbox',options:{precision:2}}
		}, {
			field : 'politicsFinalTermScore',
			title : '政治期末成绩',
			editor: {type:'numberbox',options:{precision:2}}
		}, {
			field : 'politicsTotalAvgScore',
			title : '政治总平成绩',
			editor: {type:'numberbox',options:{precision:2}}
		}, {
			field : 'politicsFinalTermGradeAvgScore',
			title : '政治期末级平均分',
			editor: {type:'numberbox'}
		}, {
			field : 'chineseNormalScore',
			title : '语文平时成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'chineseFinalTermScore',
			title : '语文期末成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'chineseTotalAvgScore',
			title : '语文总平成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'chineseFinalTermGradeAvgScore',
			title : '语文期末级平均分',
			editor: {type:'numberbox'}
		}, {
			field : 'chineseLanguage',
			title : '语文口语',
			editor: {type:'numberbox'}
		}, {
			field : 'mathNormalScore',
			title : '数学平时成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'mathFinalTermScore',
			title : '数学期末成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'mathTotalAvgScore',
			title : '数学总平成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'mathFinalTermGradeAvgScore',
			title : '数学期末级平均分',
			editor: {type:'numberbox'}
		}, {
			field : 'englishNormalScore',
			title : '英语平时成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'englishFinalTermScore',
			title : '英语期末成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'englishTotalAvgScore',
			title : '英语总平成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'englishFinalTermGradeAvgScore',
			title : '英语期末级平均分',
			editor: {type:'numberbox'}
		}, {
			field : 'englishLanguage',
			title : '英语口语',
			editor: {type:'numberbox'}
		}, {
			field : 'biologyNormalScore',
			title : '生物平时成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'biologyFinalTermScore',
			title : '生物期末成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'biologyTotalAvgScore',
			title : '生物总平成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'biologyFinalTermGradeAvgScore',
			title : '生物期末级平均分',
			editor: {type:'numberbox'}
		}, {
			field : 'phyticsNormalScore',
			title : '物理平时成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'phyticsFinalTermScore',
			title : '物理期末成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'phyticsTotalAvgScore',
			title : '物理总平成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'phyticsFinalTermGradeAvgScore',
			title : '物理期末级平均分',
			editor: {type:'numberbox'}
		}, {
			field : 'chemistryNormalScore',
			title : '化学平时成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'chemistryFinalTermScore',
			title : '化学期末成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'chemistryTotalAvgScore',
			title : '化学总平成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'chemistryFinalTermGradeAvgScore',
			title : '化学期末级平均分',
			editor: {type:'numberbox'}
		}, {
			field : 'historyNormalScore',
			title : '历史平时成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'historyFinalTermScore',
			title : '历史期末成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'historyTotalAvgScore',
			title : '历史总平成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'historyFinalTermGradeAvgScore',
			title : '历史期末级平均分',
			editor: {type:'numberbox'}
		}, {
			field : 'geographyNormalScore',
			title : '地理平时成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'geographyFinalTermScore',
			title : '地理期末成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'geographyTotalAvgScore',
			title : '地理总平成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'geographyFinalTermGradeAvgScore',
			title : '地理期末级平均分',
			editor: {type:'numberbox'}
		}, {
			field : 'sportsNormalScore',
			title : '体育平时成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'sportsFinalTermScore',
			title : '体育期末成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'sportsTotalAvgScore',
			title : '体育总平成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'musicTotalAvgScore',
			title : '音乐总平成绩',
			editor: {type:'textbox'}
		}, {
			field : 'artTotalAvgScore',
			title : '美术总平成绩',
			editor: {type:'textbox'}
		}, {
			field : 'infomationNormalScore',
			title : '信息平时成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'infomationFinalTermScore',
			title : '信息期末成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'infomationTotalAvgScore',
			title : '信息总平成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'synthesizeTotalAvgScore',
			title : '综合总平成绩',
			editor: {type:'numberbox'}
		}, {
			field : 'conductScore',
			title : '操行分',
			editor: {type:'numberbox'}
		}, {
			field : 'moralEducationLevel',
			title : '德育等级',
			editor: {type:'textbox'}
		}, {
			field : 'prizeItems',
			title : '获奖情况',
			width: 200,
			editor: {type:'textbox'},
			formatter: function(value, row, index) {
				return  '<span title="' + value + '" class="note">' + value + '</span>';
			}
		}, {
			field : 'teacherComment',
			title : '评语',
			width: 200,
			editor: {type:'textbox'},
			formatter: function(value, row, index) {
				return  '<span title="' + value + '" class="note">' + value + '</span>';
			}
		}
		] ],
		onLoadSuccess: function(data){
	        $(".note").tooltip({
		        onShow: function () {
			        $(this).tooltip('tip').css({
			       		borderColor: '#000'
			        });
		        }
	        });
		},
		onAfterEdit : function(rowIndex, rowData, changes){
			if(rowData.id){
				changes.id = rowData.id;
				addmodify(changes)
			}
		}
		
	});
}

function reload() {
	dataGrid.datagrid("clearSelections");
	dataGrid.datagrid('load');
}

function searchForm(formId) {
	dataGrid.datagrid('load', $.serializeObject($('#' + formId)));
}
function resetForm(formId) {
	$("#" + formId)[0].reset();
}

function initGradeList(termName) {
	var termYear = termName.substring(0, termName.indexOf("-"))
	$.ajax({
 		url : basePath + "/gradeByTermYear",
 		type : "post",
 		dataType : "json",
 		data: {
 			termYear: termYear
 		},
 		async : false,
 		success : function(data) {
 			var html = '';
 			for(var i in data){
 		        html += "<option value='"+data[i].value+"'>"+ data[i].text +"</option>";
 		    }
 			$("#grade").html(html);
 			$("#grade").trigger("onchange");
 		}, error:function(){
 			alert("查询年级异常");
  		}
    });
}
function searchGrade() {
	initGradeList($("#termId option:selected")[0].text);
}
function searchClazz(grade) {
	if(!grade) return;
	$.ajax({
 		url : basePath + "/getFullClazz?grade=" + grade,
 		type : "GET",
 		dataType : "json",
 		async : false,
 		success : function(data) {
 			var html = '';
 			for(var i in data){
 		        if (data.hasOwnProperty(i)) {
 		        	html += "<option value='"+data[i]+"'>"+ data[i] +"班</option>";
 		        };
 		    }
 			$("#clazz").html(html);
 			if(!dataGrid){
 				loadData();
 			}
 		}, error:function(){
 			alert("查询班级异常");
  		}
    });
}

function batchCreatePdf(formId) {
	$.messager.confirm('系统提示', '是否确认批量生成成长足迹', function(r) {
		if (r){
			$.ajax({
				url : batchCreatePdfUrl,
				type : 'POST',
				error : function() {
					$.messager.progress('close');
					$.messager.alert('系统提示', '操作异常', 'error');
				},
				data : $('#' + formId).serialize(),
				success : function(data) {
					$.messager.progress('close');
					if (data.code == '000') {
						$.messager.alert('系统提示', '批量提交生成,请过几分钟再查看结果', 'info');
					} else {
						$.messager.alert('系统提示', '批量提交失败', 'warning');
					}
				}
			});
		}
	});
}

function initTermList(){
    $.ajax({
        url: termListUrl,
        type: 'POST',
        dataType: 'json',
        error : function(data) {
            $.messager.progress('close');
            $.messager.alert('系统提示', data.msg, 'error');
        },
        success: function (data) {
        	var html = "";
        	for(var i in data) {
        		html += "<option value='"+data[i].id+"'>"+data[i].termName+"</option>";
        	}
            $("#termId").html(html);
            initGradeList(data[0].termName);
        }
    });
}
var uploadBox;
function upload() {
	var termId = $("#termId option:selected")[0].text;
	var termType = $("#termType option:selected")[0].text;
	var grade = $("#grade option:selected")[0].text;
	var clazz = $("#clazz option:selected")[0].text;
	$("#scoreTips").html("<span class='calendar-sunday'>确认选择上传" + termId + "(" + termType + ")" + grade + "(" + clazz + ")成绩，以免成绩上传出错</span>");
	uploadBox = $('#uploadBox').dialog({
		title : '上传期末成绩报告',
		modal : true,
		width : 400,
		top : 200,
		draggable : true,
		resizable : true,
		buttons : '#btns',
		onClose : function() {
			$('#files').filebox('setValue','');
		}
	}).show();
}

function uploadCommit(){
	var fileObj = document.getElementById('filebox_file_id_2').files[0];
	if(!fileObj) {
		$.messager.alert('提醒','请选择文件');
		return;
	}
	$.messager.progress({
		title : '提示',
		msg : '上传中，请稍候...'
	});
	var xhr = new XMLHttpRequest();
	xhr.open('POST', basePath + "/sys/file/classTermReport/import");
	xhr.onload = function () {
       if (xhr.status === 200) {
    	    $.messager.progress('close');
	       	var resp = JSON.parse(xhr.response);
	       	if(resp.code == '000') {
	       		$.messager.alert("成功","上传成功！","info");
	       		loadData();
	       		$('#files').filebox('setValue','');
	       		uploadBox.dialog('close');
	       	}else {
	       		$.messager.alert('错误提醒', resp.msg);
	       	}
       }
   };
   xhr.onerror = function () {
	   $.messager.progress('close');
	   $.messager.alert('错误', "上传异常");
   };
   var gradeA = $("#grade").val().split(",");
   var fd = new FormData();
   fd.append('files', fileObj);
   fd.append("termId", $("#termId").val());
   fd.append("termType", $("#termType").val());
   fd.append("grade", gradeA[0]);
   fd.append("studyType", gradeA[1]);
   fd.append("clazz", $("#clazz").val());
   // 触发上传
	setTimeout(function() {
		xhr.send(fd);
	}, 1000)
}

var cleanFormPanel=function(formId){
	$('#' + formId)[0].reset();
}

function save(id) {
	if(dgEditIndex[id] != null){
		$('#' + id).datagrid('endEdit', dgEditIndex[id]);
		dgEdit[id] = null;
	}
}
function addmodify(data) {
	$.ajax({
	   type: "POST",
	   url: updateStudentTermReport,
	   data: data,
	   success: function(res){
		   if (res.code == '000'){
			   reload();
			   $.messager.alert('提示', '提交成功', 'info');
		   }else{
			   $.messager.alert('提示', '提交失败', 'error');
			   errorEdit("studentDg");
		   }
		},
		error: function() {
			alert("提交异常");
			errorEdit("studentDg");
		}
	});
}

function exportToExcel(searchForm,exportUrl) {
	$("#" + searchForm).attr('action',exportUrl);
	$("#" + searchForm).submit();  
}